package aspect;

import annotation.PrivilegeAnnotationParse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import privilege.UserPrivilege;

import java.util.List;

@Aspect
public class PrivilegeAspect {

    private List<UserPrivilege> privileges;

    public List<UserPrivilege> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(List<UserPrivilege> privileges) {
        this.privileges = privileges;
    }

    @Pointcut("execution(* service..*.*(..))")
    public void privilegeService() { }


    @Around("privilegeService()")
    public void isPrivilege(ProceedingJoinPoint joinPoint) throws Throwable {
        //根据解析器可知  我们需要先获取类和方法名
        Class clazz = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("-------------------------------------------");
        System.out.println("拦截到了方法"+clazz.getName()+"."+methodName);
        String privilege = PrivilegeAnnotationParse.parse(clazz,methodName);
        System.out.println("\n该方法的权限是:"+privilege);
        boolean isAccess = false;
        if(privilege.equals(""))
            isAccess = true;
        else {
            for (UserPrivilege p : privileges) {
                if (p.getName().equals(privilege)){
                    isAccess = true;
                    break;
                }
            }
        }
        if(isAccess){
            System.out.print("\n执行结果:");
            joinPoint.proceed();
        }else{
            System.out.println("\n无权限执行方法:"+clazz.getName()+"."+methodName);
        }
        System.out.println("-------------------------------------------");
    }
}
